// 确保UnoCSS在最前面导入
import 'virtual:uno.css';
// 导入样式
import './style.css';
// 导入情感化设计增强
import './emotional-design.css';

// 导入可访问性色彩对比度优化
import './accessibility-colors.css';

// 导入情感化设计交互功能
import './emotional-design.js';

// 定义菜单接口
interface MenuItem {
  id: string;
  name: string;
  icon: string;
  path: string;
  iframeSrc?: string;
  children?: MenuItem[];
}

// 定义Tab接口
interface TabItem {
  id: string;
  name: string;
  path: string;
  iframeSrc?: string;
}

// 全局变量
let currentPath = '/dashboard';
let menus: MenuItem[] = [];
let tabs: TabItem[] = [];
let activeTabId = '';
let isSidebarCollapsed = false;
let isSidebarHidden = false;
let breadcrumbData: { name: string; path: string }[] = [];

// 从JSON文件加载菜单数据
async function loadMenuData() {
  try {
    // 尝试不同的路径以确保兼容性
    let response;
    try {
      // 首先尝试相对路径
      response = await fetch('./src/config/menuConfig.json');
    } catch {
      // 如果失败，尝试相对于comp-web的路径
      response = await fetch('/comp-web/src/config/menuConfig.json');
    }
    
    if (!response.ok) {
      throw new Error('Failed to load menu config');
    }
    menus = await response.json();
  } catch (error) {
    console.error('Error loading menu data:', error);
    // 提供默认菜单数据作为降级方案
    menus = [
      { id: 'dashboard', name: '首页', icon: '🏠', path: '/dashboard' },
      { id: 'user', name: '用户管理', icon: '👥', path: '/user', children: [
        { id: 'user-list', name: '用户列表', icon: '📋', path: '/user/list' },
        { id: 'user-add', name: '添加用户', icon: '➕', path: '/user/add' }
      ]},
      { id: 'system', name: '系统设置', icon: '⚙️', path: '/system', children: [
        { id: 'system-config', name: '系统配置', icon: '🔧', path: '/system/config' },
        { id: 'system-log', name: '系统日志', icon: '📝', path: '/system/log' }
      ]},
      { id: 'about', name: '关于系统', icon: 'ℹ️', path: '/about' }
    ];
  }
}

// 创建完整的后台管理系统布局
function createAdminLayout() {
  const app = document.getElementById('app');
  if (!app) return;

  // 清空现有内容
  app.innerHTML = '';

  // 创建主容器
  const container = document.createElement('div');
  container.className = 'flex w-full h-screen bg-[radial-gradient(rgba(0,0,0,0.05)_1px,transparent_1px)] bg-[size:20px_20px] overflow-hidden';

  // 创建左侧菜单栏
  const sidebar = document.createElement('aside');
  sidebar.id = 'sidebar';
  sidebar.className = 'w-64 bg-white/90 border-r border-[rgba(59,130,246,0.4)] shadow-sm flex flex-col overflow-y-auto transition-all duration-300 ease-in-out';

  // 创建右侧主内容区容器
  const rightContent = document.createElement('div');
  rightContent.id = 'right-content';
  rightContent.className = 'flex-1 flex flex-col overflow-hidden transition-all duration-300 ease-in-out';

  // 创建顶部导航栏
  const topbar = document.createElement('header');
  topbar.id = 'topbar';
  topbar.className = 'h-16 bg-white/90 border-b border-[rgba(59,130,246,0.4)] shadow-sm flex items-center justify-between px-6 w-full';

  // 创建主内容区
  const mainContent = document.createElement('main');
  mainContent.id = 'main-content';
  mainContent.className = 'flex-1 flex flex-col overflow-hidden';

  // 创建Tab栏
  const tabBar = document.createElement('div');
  tabBar.id = 'tab-bar';
  tabBar.className = 'h-10 bg-white/90 border-b border-[rgba(59,130,246,0.4)] flex items-center px-3 overflow-x-auto overflow-y-hidden space-x-1 no-scrollbar';
  tabBar.style.minHeight = '40px';
  tabBar.style.maxHeight = '40px';

  // 创建内容展示区
  const contentArea = document.createElement('div');
  contentArea.id = 'content-area';
  contentArea.className = 'flex-1 overflow-hidden';

  // 构建完整DOM结构
  mainContent.appendChild(tabBar);
  mainContent.appendChild(contentArea);
  rightContent.appendChild(topbar);
  rightContent.appendChild(mainContent);
  container.appendChild(sidebar);
  container.appendChild(rightContent);
  app.appendChild(container);

  // 渲染各个组件
  renderSidebar();
  renderTopbar();
  addDefaultTab();
}

// 渲染左侧菜单栏
function renderSidebar() {
  const sidebar = document.getElementById('sidebar');
  if (!sidebar) return;
  
  // 为侧边栏添加相对定位，使底部折叠按钮能正确定位（保留原有样式）
  sidebar.classList.add('relative');

  // 创建侧边栏头部
  const sidebarHeader = document.createElement('div');
  sidebarHeader.className = 'h-16 flex items-center justify-between px-4 border-b border-[rgba(59,130,246,0.4)]';
  
  // 系统标题
  const title = document.createElement('h2');
  title.className = 'text-xl font-bold text-[#334155] transition-all duration-300';
  title.textContent = '系统管理平台';
  
  sidebarHeader.appendChild(title);
  sidebar.appendChild(sidebarHeader);

  // 创建菜单搜索框（UED优化设计）
  const searchContainer = document.createElement('div');
  searchContainer.className = 'p-4 border-b';
  searchContainer.style.borderColor = 'rgba(191, 219, 254, 1)'; // 使用内联样式确保边框颜色正确显示
  searchContainer.innerHTML = `
    <input 
      type="text" 
      id="menu-search" 
      placeholder="搜索菜单..." 
      class="w-full px-4 py-3 bg-white/95 border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-blue-500 transition-all duration-300 placeholder:text-slate-400 text-slate-700 backdrop-blur-sm shadow-sm hover:shadow-md"
      style="border-color: rgba(147, 197, 253, 1);"
    >
  `;
  sidebar.appendChild(searchContainer);

  // 创建菜单容器
  const menuContainer = document.createElement('div');
  menuContainer.id = 'menu-container';
  menuContainer.className = 'p-4 flex-1 space-y-6 overflow-y-auto overflow-x-hidden';

  // 绑定搜索事件
  const searchInput = document.getElementById('menu-search') as HTMLInputElement;
  if (searchInput) {
    // 确保搜索框边框颜色正确显示
    searchInput.style.borderColor = 'rgba(147, 197, 253, 1)';
    
    searchInput.addEventListener('input', function() {
      filterMenuItems(this.value);
    });
  }

  // 递归渲染菜单
  function renderMenuItems(menuItems: MenuItem[], parentElement: HTMLElement) {
    const ul = document.createElement('ul');
    ul.className = 'space-y-2';

    menuItems.forEach(function(menu) {
      const isActive = menu.path === currentPath;
      const li = document.createElement('li');

      // 创建菜单项
      const menuLink = document.createElement('a');
      menuLink.href = 'javascript:void(0)';
      menuLink.className = `flex items-center px-4 py-3 rounded-lg transition-all duration-300 ${isActive ? 'bg-[rgba(59,130,246,0.15)] text-[#3b82f6] font-medium border-l-3 border-[#3b82f6]' : 'hover:bg-gray-100 text-[#64748b]'}`;
      menuLink.setAttribute('data-path', menu.path);
      menuLink.setAttribute('data-id', menu.id);
      if (menu.iframeSrc) {
        menuLink.setAttribute('data-iframe-src', menu.iframeSrc);
      }

      // 菜单图标
      const iconSpan = document.createElement('span');
      iconSpan.className = 'menu-icon text-lg mr-3';
      iconSpan.textContent = menu.icon;

      // 菜单名称
      const nameSpan = document.createElement('span');
      nameSpan.className = 'text-base';
      nameSpan.textContent = menu.name;

      // 子菜单箭头（如果有子菜单）
      let arrowSpan: HTMLElement | null = null;
      if (menu.children && menu.children.length > 0) {
        arrowSpan = document.createElement('span');
        arrowSpan.className = 'ml-auto text-sm transition-transform duration-300';
        arrowSpan.textContent = '▼';
      }

      // 构建菜单项
      menuLink.appendChild(iconSpan);
      menuLink.appendChild(nameSpan);
      if (arrowSpan) {
        menuLink.appendChild(arrowSpan);
      }

      // 处理点击事件
      menuLink.addEventListener('click', function(e) {
        e.preventDefault();
        const path = this.getAttribute('data-path');
        const iframeSrc = this.getAttribute('data-iframe-src');
        if (path) {
          openTab(path, menu.name, iframeSrc);
        }
      });

      li.appendChild(menuLink);

      // 渲染子菜单（如果有）
      if (menu.children && menu.children.length > 0) {
        const subMenuContainer = document.createElement('div');
        subMenuContainer.className = 'pl-12 mt-1 space-y-2';
        renderMenuItems(menu.children, subMenuContainer);
        li.appendChild(subMenuContainer);
      }

      ul.appendChild(li);
    });

    parentElement.appendChild(ul);
  }

  renderMenuItems(menus, menuContainer);
  sidebar.appendChild(menuContainer);

  // 创建侧边栏底部折叠按钮（固定在左下角）
  const sidebarFooter = document.createElement('div');
  sidebarFooter.className = 'absolute bottom-0 left-0 right-0 p-3 border-t border-[rgba(59,130,246,0.1)] bg-white/95 backdrop-blur-sm';
  
  const collapseBtn = document.createElement('button');
  collapseBtn.id = 'collapse-btn';
  collapseBtn.className = 'w-10 h-10 rounded-xl flex items-center justify-center text-[#64748b] hover:bg-[rgba(59,130,246,0.1)] hover:text-[#3b82f6] transition-all duration-300 shadow-sm hover:shadow-md';
  collapseBtn.innerHTML = '<span class="text-xl">⇄</span>';
  collapseBtn.title = '折叠/展开菜单';
  collapseBtn.addEventListener('click', function() {
    toggleSidebar();
  });
  
  sidebarFooter.appendChild(collapseBtn);
  sidebar.appendChild(sidebarFooter);
  
  // 初始化折叠按钮状态
  updateCollapseButtonState();
}

// 渲染顶部菜单栏
function renderTopbar() {
  const topbar = document.getElementById('topbar');
  if (!topbar) return;

  // 左侧区域（面包屑和菜单切换按钮）
  const leftSection = document.createElement('div');
  leftSection.className = 'flex items-center space-x-4';
  
  // 移动端菜单切换按钮（响应式）
  const menuToggle = document.createElement('button');
  menuToggle.id = 'menu-toggle';
  menuToggle.className = 'lg:hidden w-8 h-8 rounded-lg flex items-center justify-center text-[#64748b] hover:bg-gray-100 transition-all duration-300';
  menuToggle.innerHTML = '<span class="text-lg">☰</span>';
  menuToggle.addEventListener('click', function() {
    toggleMobileMenu();
  });
  
  // 面包屑导航
  const breadcrumb = document.createElement('div');
  breadcrumb.id = 'breadcrumb';
  breadcrumb.className = 'flex items-center space-x-2 text-sm';
  
  leftSection.appendChild(menuToggle);
  leftSection.appendChild(breadcrumb);
  
  // 右侧用户信息区域（优化布局，充分利用空间）
  const rightSection = document.createElement('div');
  rightSection.className = 'flex items-center space-x-8';
  
  // 通知按钮
  const notificationBtn = document.createElement('button');
  notificationBtn.className = 'relative w-10 h-10 rounded-xl flex items-center justify-center text-[#64748b] hover:bg-gray-100 transition-all duration-300';
  notificationBtn.innerHTML = `
    <span class="text-2xl">🔔</span>
    <span class="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full"></span>
  `;
  
  // 主题切换按钮
  const themeToggle = document.createElement('button');
  themeToggle.id = 'theme-toggle';
  themeToggle.className = 'w-10 h-10 rounded-xl flex items-center justify-center text-[#64748b] hover:bg-gray-100 transition-all duration-300';
  themeToggle.innerHTML = '<span class="text-2xl">🌙</span>';
  themeToggle.addEventListener('click', function() {
    toggleTheme();
  });
  
  // 用户信息下拉菜单（优化布局，增加间距）
  const userDropdown = document.createElement('div');
  userDropdown.className = 'relative';
  userDropdown.innerHTML = `
    <button id="user-dropdown-btn" class="flex items-center space-x-4 px-4 py-3 rounded-xl hover:bg-gray-100 transition-all duration-300">
      <div class="w-10 h-10 rounded-full bg-gradient-to-r from-blue-400 to-purple-500 flex items-center justify-center shadow-md">
        <span class="text-base font-bold text-white">A</span>
      </div>
      <div class="flex flex-col items-start">
        <span class="text-base font-semibold text-[#334155]">管理员</span>
        <span class="text-sm text-[#64748b]">超级管理员</span>
      </div>
      <span id="user-dropdown-icon" class="text-[#64748b] text-lg transition-transform duration-300">▼</span>
    </button>
    <div id="user-dropdown-menu" class="absolute top-full right-0 mt-3 w-56 bg-white/95 backdrop-blur-sm rounded-xl shadow-lg border border-gray-200 py-3 hidden z-50">
      <a href="javascript:void(0)" class="block px-5 py-3 text-sm text-[#334155] hover:bg-gray-50 transition-colors duration-200">个人中心</a>
      <a href="javascript:void(0)" class="block px-5 py-3 text-sm text-[#334155] hover:bg-gray-50 transition-colors duration-200">账号设置</a>
      <div class="border-t border-gray-200 my-3"></div>
      <a href="javascript:void(0)" class="block px-5 py-3 text-sm text-red-500 hover:bg-red-50 transition-colors duration-200">退出登录</a>
    </div>
  `;
  
  rightSection.appendChild(notificationBtn);
  rightSection.appendChild(themeToggle);
  rightSection.appendChild(userDropdown);
  
  topbar.appendChild(leftSection);
  topbar.appendChild(rightSection);
  
  // 更新面包屑
  updateBreadcrumb();
  
  // 绑定用户下拉菜单事件
  bindUserDropdownEvents();
}

// 添加默认Tab
function addDefaultTab() {
  const menuItem = findMenuItemByPath(currentPath);
  if (menuItem) {
    openTab(currentPath, menuItem.name, menuItem.iframeSrc);
  }
}

// 根据路径查找菜单项
function findMenuItemByPath(path: string): MenuItem | null {
  // 先在一级菜单中查找
  const menuItem = menus.find(function(menu) {
    return menu.path === path;
  });
  if (menuItem) {
    return menuItem;
  }
  
  // 再在所有子菜单中查找
  for (const menu of menus) {
    if (menu.children) {
      const subMenuItem = menu.children.find(function(subMenu) {
        return subMenu.path === path;
      });
      if (subMenuItem) {
        return subMenuItem;
      }
    }
  }
  
  return null;
}

// 打开Tab
function openTab(path: string, name: string, iframeSrc?: string) {
  // 检查Tab是否已存在
  let tab = tabs.find(function(t) {
    return t.path === path;
  });

  // 如果Tab不存在，创建新Tab
  if (!tab) {
    tab = {
      id: 'tab-' + Date.now(),
      name: name,
      path: path,
      iframeSrc: iframeSrc
    };
    tabs.push(tab);
  }

  // 设置当前活动Tab
  activeTabId = tab.id;
  currentPath = path;

  // 重新渲染Tab栏和内容
  renderTabs();
  renderTabContent(tab);

  // 更新左侧菜单选中状态
  updateSidebarActiveState(path);
  
  // 更新面包屑导航
  updateBreadcrumb();
}

// 渲染Tab栏
function renderTabs() {
  const tabBar = document.getElementById('tab-bar');
  if (!tabBar) return;

  tabBar.innerHTML = '';

  tabs.forEach(function(tab, index) {
    const isActive = tab.id === activeTabId;
    const tabItem = document.createElement('div');
    tabItem.className = `tab-item ${isActive ? 'active' : ''}`;
    tabItem.setAttribute('data-tab-id', tab.id);
    tabItem.setAttribute('data-tab-index', index.toString());
    tabItem.draggable = true;

    // Tab名称（限制最多显示5个字符）
    const tabName = document.createElement('span');
    tabName.className = 'tab-name';
    tabName.textContent = tab.name.length > 5 ? tab.name.substring(0, 5) + '...' : tab.name;
    tabName.title = tab.name; // 鼠标悬停显示完整名称

    // 关闭按钮
    const closeBtn = document.createElement('button');
    closeBtn.className = 'tab-close-btn';
    closeBtn.textContent = '×';
    closeBtn.setAttribute('aria-label', '关闭标签页');
    closeBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      closeTab(tab.id);
    });

    tabItem.appendChild(tabName);
    tabItem.appendChild(closeBtn);

    // 点击Tab切换内容
    tabItem.addEventListener('click', function() {
      activeTabId = tab.id;
      currentPath = tab.path;
      renderTabs();
      renderTabContent(tab);
      updateSidebarActiveState(tab.path);
    });

    // 右键菜单
    tabItem.addEventListener('contextmenu', function(e) {
      e.preventDefault();
      showTabContextMenu(e, tab, index);
    });

    // 拖拽事件
    tabItem.addEventListener('dragstart', function(e) {
      e.dataTransfer?.setData('text/plain', index.toString());
      tabItem.classList.add('opacity-50');
    });

    tabItem.addEventListener('dragend', function() {
      tabItem.classList.remove('opacity-50');
    });

    tabItem.addEventListener('dragover', function(e) {
      e.preventDefault();
      tabItem.classList.add('bg-blue-100');
    });

    tabItem.addEventListener('dragleave', function() {
      tabItem.classList.remove('bg-blue-100');
    });

    tabItem.addEventListener('drop', function(e) {
      e.preventDefault();
      tabItem.classList.remove('bg-blue-100');
      
      const fromIndex = parseInt(e.dataTransfer?.getData('text/plain') || '0');
      const toIndex = index;
      
      if (fromIndex !== toIndex) {
        moveTab(fromIndex, toIndex);
      }
    });

    tabBar.appendChild(tabItem);
  });
}

// 关闭Tab
function closeTab(tabId: string) {
  const tabIndex = tabs.findIndex(function(tab) {
    return tab.id === tabId;
  });

  if (tabIndex === -1) return;

  // 如果关闭的是当前活动Tab，切换到其他Tab
  if (tabId === activeTabId) {
    let newActiveIndex;
    if (tabIndex > 0) {
      newActiveIndex = tabIndex - 1;
    } else if (tabs.length > 1) {
      newActiveIndex = tabIndex + 1;
    } else {
      // 如果只有一个Tab，不允许关闭
      return;
    }

    const newActiveTab = tabs[newActiveIndex];
    activeTabId = newActiveTab.id;
    currentPath = newActiveTab.path;
    renderTabContent(newActiveTab);
    updateSidebarActiveState(newActiveTab.path);
  }

  // 移除Tab
  tabs.splice(tabIndex, 1);
  renderTabs();
}

// 移动Tab位置
function moveTab(fromIndex: number, toIndex: number) {
  if (fromIndex === toIndex) return;
  
  const tab = tabs[fromIndex];
  tabs.splice(fromIndex, 1);
  tabs.splice(toIndex, 0, tab);
  
  renderTabs();
}

// 显示Tab右键菜单
function showTabContextMenu(e: MouseEvent, tab: TabItem, index: number) {
  // 移除现有的右键菜单
  const existingMenu = document.getElementById('tab-context-menu');
  if (existingMenu) {
    existingMenu.remove();
  }

  const contextMenu = document.createElement('div');
  contextMenu.id = 'tab-context-menu';
  contextMenu.className = 'fixed bg-white shadow-lg rounded-lg py-2 z-50 min-w-[120px] border border-gray-200';
  contextMenu.style.left = e.pageX + 'px';
  contextMenu.style.top = e.pageY + 'px';

  // 菜单选项
  const menuItems = [
    { text: '关闭', action: function() { closeTab(tab.id); } },
    { text: '关闭其他', action: function() { closeOtherTabs(tab.id); } },
    { text: '关闭所有', action: function() { closeAllTabs(); } },
    { text: '刷新', action: function() { refreshTab(tab.id); } },
    { text: '复制路径', action: function() { copyTabPath(tab.path); } }
  ];

  menuItems.forEach(function(item) {
    const menuItem = document.createElement('div');
    menuItem.className = 'px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer transition-colors duration-200';
    menuItem.textContent = item.text;
    menuItem.addEventListener('click', function() {
      item.action();
      contextMenu.remove();
    });
    contextMenu.appendChild(menuItem);
  });

  document.body.appendChild(contextMenu);

  // 点击其他地方关闭菜单
  function closeMenu() {
    contextMenu.remove();
    document.removeEventListener('click', closeMenu);
  }

  setTimeout(function() {
    document.addEventListener('click', closeMenu);
  }, 100);
}

// 关闭其他Tab
function closeOtherTabs(currentTabId: string) {
  tabs = tabs.filter(function(tab) {
    return tab.id === currentTabId;
  });
  
  activeTabId = currentTabId;
  currentPath = tabs[0]?.path || '/dashboard';
  renderTabs();
  renderTabContent(tabs[0]);
  updateSidebarActiveState(currentPath);
}

// 关闭所有Tab
function closeAllTabs() {
  tabs = [];
  activeTabId = '';
  currentPath = '/dashboard';
  renderTabs();
  
  // 重新打开仪表盘
  setTimeout(function() {
    openTab('/dashboard', '仪表盘');
  }, 100);
}

// 刷新Tab
function refreshTab(tabId: string) {
  const tab = tabs.find(function(t) {
    return t.id === tabId;
  });
  
  if (tab) {
    renderTabContent(tab);
  }
}

// 复制Tab路径
function copyTabPath(path: string) {
  navigator.clipboard.writeText(path).then(function() {
    // 显示复制成功提示
    showToast('路径已复制到剪贴板');
  }).catch(function() {
    showToast('复制失败');
  });
}

// 显示Toast提示
function showToast(message: string) {
  const toast = document.createElement('div');
  toast.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50 transition-all duration-300';
  toast.textContent = message;
  
  document.body.appendChild(toast);
  
  setTimeout(function() {
    toast.style.transform = 'translateY(-100px)';
    toast.style.opacity = '0';
    setTimeout(function() {
      toast.remove();
    }, 300);
  }, 2000);
}

// 渲染Tab内容
function renderTabContent(tab: TabItem) {
  const contentArea = document.getElementById('content-area');
  if (!contentArea) return;

  // 清空现有内容
  contentArea.innerHTML = '';

  // 如果有iframeSrc，使用iframe展示
  if (tab.iframeSrc) {
    const iframe = document.createElement('iframe');
    iframe.src = tab.iframeSrc;
    iframe.className = 'w-full h-full border-0';
    contentArea.appendChild(iframe);
    return;
  }

  // 根据路径渲染内容
  const contentContainer = document.createElement('div');
  contentContainer.className = 'p-6 overflow-y-auto h-full';

  let content = '';
  
  switch (tab.path) {
    case '/dashboard':
      content = `
        <!-- 数据卡片区域 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <!-- 用户总数卡片 -->
          <div class="bg-white/90 border border-[rgba(59,130,246,0.4)] rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.02)] p-6 transition-all duration-300 hover:shadow-[0_6px_16px_rgba(0,0,0,0.04)] hover:translate-y-[-2px]">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-xs text-[#64748b] mb-1">用户总数</p>
                <h3 class="text-3xl font-bold text-[#334155]">12,345</h3>
                <p class="text-xs text-green-500 mt-1 flex items-center">
                  <span class="mr-1">↑</span> 5.2%
                </p>
              </div>
              <div class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center text-blue-500">
                👥
              </div>
            </div>
            <!-- 进度条 -->
            <div class="mt-4">
              <div class="w-full bg-gray-200 rounded-full h-2">
                <div class="bg-blue-500 h-2 rounded-full" style="width: 75%"></div>
              </div>
              <p class="text-xs text-[#64748b] mt-1">目标: 16,000</p>
            </div>
          </div>
          
          <!-- 今日访问卡片 -->
          <div class="bg-white/90 border border-[rgba(59,130,246,0.4)] rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.02)] p-6 transition-all duration-300 hover:shadow-[0_6px_16px_rgba(0,0,0,0.04)] hover:translate-y-[-2px]">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-xs text-[#64748b] mb-1">今日访问</p>
                <h3 class="text-3xl font-bold text-[#334155]">2,890</h3>
                <p class="text-xs text-red-500 mt-1 flex items-center">
                  <span class="mr-1">↓</span> 2.1%
                </p>
              </div>
              <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center text-green-500">
                📊
              </div>
            </div>
            <!-- 趋势图 -->
            <div class="mt-4 flex items-center space-x-1">
              <div class="w-3 h-8 bg-green-400 rounded-t"></div>
              <div class="w-3 h-10 bg-green-500 rounded-t"></div>
              <div class="w-3 h-12 bg-green-600 rounded-t"></div>
              <div class="w-3 h-14 bg-green-700 rounded-t"></div>
              <div class="w-3 h-10 bg-green-500 rounded-t"></div>
              <div class="w-3 h-8 bg-green-400 rounded-t"></div>
            </div>
          </div>
          
          <!-- 待处理任务卡片 -->
          <div class="bg-white/90 border border-[rgba(59,130,246,0.4)] rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.02)] p-6 transition-all duration-300 hover:shadow-[0_6px_16px_rgba(0,0,0,0.04)] hover:translate-y-[-2px]">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-xs text-[#64748b] mb-1">待处理任务</p>
                <h3 class="text-3xl font-bold text-[#334155]">128</h3>
                <p class="text-xs text-blue-500 mt-1 flex items-center">
                  <span class="mr-1">↑</span> 10.5%
                </p>
              </div>
              <div class="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center text-purple-500">
                📝
              </div>
            </div>
            <!-- 任务分布 -->
            <div class="mt-4 flex justify-between text-xs text-[#64748b]">
              <span>高优先级: 32</span>
              <span>中优先级: 64</span>
              <span>低优先级: 32</span>
            </div>
          </div>
          
          <!-- 收入统计卡片 -->
          <div class="bg-white/90 border border-[rgba(59,130,246,0.4)] rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.02)] p-6 transition-all duration-300 hover:shadow-[0_6px_16px_rgba(0,0,0,0.04)] hover:translate-y-[-2px]">
            <div class="flex items-center justify-between">
              <div>
                <p class="text-xs text-[#64748b] mb-1">本月收入</p>
                <h3 class="text-3xl font-bold text-[#334155]">¥89,456</h3>
                <p class="text-xs text-green-500 mt-1 flex items-center">
                  <span class="mr-1">↑</span> 15.8%
                </p>
              </div>
              <div class="w-12 h-12 rounded-full bg-yellow-100 flex items-center justify-center text-yellow-500">
                💰
              </div>
            </div>
            <!-- 环形进度 -->
            <div class="mt-4 relative w-16 h-16 mx-auto">
              <svg class="w-full h-full" viewBox="0 0 36 36">
                <path d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" fill="none" stroke="#e2e8f0" stroke-width="3"/>
                <path d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" fill="none" stroke="#f59e0b" stroke-width="3" stroke-dasharray="75, 100"/>
              </svg>
              <span class="absolute inset-0 flex items-center justify-center text-xs font-bold text-[#334155]">75%</span>
            </div>
          </div>
        </div>
        
        <!-- 图表区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
          <!-- 访问量趋势图 -->
          <div class="bg-white/90 border border-[rgba(59,130,246,0.4)] rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.02)] p-6">
            <h3 class="text-lg font-bold text-[#334155] mb-4">访问量趋势</h3>
            <div class="h-48 flex items-end space-x-2">
              <div class="flex-1 flex flex-col items-center">
                <div class="w-full bg-gradient-to-t from-blue-400 to-blue-600 rounded-t" style="height: 60%"></div>
                <span class="text-xs text-[#64748b] mt-2">周一</span>
              </div>
              <div class="flex-1 flex flex-col items-center">
                <div class="w-full bg-gradient-to-t from-blue-400 to-blue-600 rounded-t" style="height: 80%"></div>
                <span class="text-xs text-[#64748b] mt-2">周二</span>
              </div>
              <div class="flex-1 flex flex-col items-center">
                <div class="w-full bg-gradient-to-t from-blue-400 to-blue-600 rounded-t" style="height: 95%"></div>
                <span class="text-xs text-[#64748b] mt-2">周三</span>
              </div>
              <div class="flex-1 flex flex-col items-center">
                <div class="w-full bg-gradient-to-t from-blue-400 to-blue-600 rounded-t" style="height: 70%"></div>
                <span class="text-xs text-[#64748b] mt-2">周四</span>
              </div>
              <div class="flex-1 flex flex-col items-center">
                <div class="w-full bg-gradient-to-t from-blue-400 to-blue-600 rounded-t" style="height: 85%"></div>
                <span class="text-xs text-[#64748b] mt-2">周五</span>
              </div>
              <div class="flex-1 flex flex-col items-center">
                <div class="w-full bg-gradient-to-t from-blue-400 to-blue-600 rounded-t" style="height: 45%"></div>
                <span class="text-xs text-[#64748b] mt-2">周六</span>
              </div>
              <div class="flex-1 flex flex-col items-center">
                <div class="w-full bg-gradient-to-t from-blue-400 to-blue-600 rounded-t" style="height: 30%"></div>
                <span class="text-xs text-[#64748b] mt-2">周日</span>
              </div>
            </div>
          </div>
          
          <!-- 用户分布饼图 -->
          <div class="bg-white/90 border border-[rgba(59,130,246,0.4)] rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.02)] p-6">
            <h3 class="text-lg font-bold text-[#334155] mb-4">用户分布</h3>
            <div class="flex items-center justify-center h-48">
              <div class="relative w-32 h-32">
                <!-- 饼图 -->
                <svg class="w-full h-full" viewBox="0 0 32 32">
                  <circle cx="16" cy="16" r="15" fill="none" stroke="#3b82f6" stroke-width="8" stroke-dasharray="25 75" transform="rotate(-90 16 16)"/>
                  <circle cx="16" cy="16" r="15" fill="none" stroke="#10b981" stroke-width="8" stroke-dasharray="40 75" stroke-dashoffset="-25" transform="rotate(-90 16 16)"/>
                  <circle cx="16" cy="16" r="15" fill="none" stroke="#f59e0b" stroke-width="8" stroke-dasharray="35 75" stroke-dashoffset="-65" transform="rotate(-90 16 16)"/>
                </svg>
                <div class="absolute inset-0 flex items-center justify-center">
                  <span class="text-lg font-bold text-[#334155]">100%</span>
                </div>
              </div>
            </div>
            <div class="flex justify-center space-x-6 text-xs">
              <div class="flex items-center">
                <div class="w-3 h-3 bg-blue-500 rounded-full mr-1"></div>
                <span>新用户 (25%)</span>
              </div>
              <div class="flex items-center">
                <div class="w-3 h-3 bg-green-500 rounded-full mr-1"></div>
                <span>活跃用户 (40%)</span>
              </div>
              <div class="flex items-center">
                <div class="w-3 h-3 bg-yellow-500 rounded-full mr-1"></div>
                <span>老用户 (35%)</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 数据表格 -->
        <div class="bg-white/90 border border-[rgba(59,130,246,0.4)] rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.02)] p-6">
          <h3 class="text-lg font-bold text-[#334155] mb-4">最近活动</h3>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead>
                <tr class="bg-gray-50">
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">用户</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">操作</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">时间</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">状态</th>
                </tr>
              </thead>
              <tbody class="divide-y divide-gray-200">
                ${Array.from({ length: 5 }, function(_, i) { return i + 1; }).map(function(id) { 
                  return `
                    <tr class="hover:bg-gray-50 transition-colors duration-150">
                      <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                          <div class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center mr-3">
                            <span class="text-sm font-medium text-gray-600">U</span>
                          </div>
                          <span class="text-sm font-medium text-gray-900">用户${id}</span>
                        </div>
                      </td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">登录系统</td>
                      <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">2023-10-0${id} 14:3${id}</td>
                      <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                          成功
                        </span>
                      </td>
                    </tr>
                  `;
                }).join('')}
              </tbody>
            </table>
          </div>
        </div>
      `;
      break;
      
    case '/user/list':
      content = `
        <div class="bg-white/90 border border-[rgba(59,130,246,0.4)] rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.02)] p-6">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-bold text-[#334155]">用户列表</h2>
            <button id="add-user-btn" class="px-4 py-2 bg-[#3b82f6] text-white rounded-lg hover:bg-[#2563eb] transition-colors duration-300">
              添加用户
            </button>
          </div>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead>
                <tr class="bg-gray-50">
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">ID</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">用户名</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">邮箱</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">角色</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">状态</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-[#64748b] uppercase">操作</th>
                </tr>
              </thead>
              <tbody class="divide-y divide-gray-200">
                ${Array.from({ length: 10 }, function(_, i) { return i + 1; }).map(function(id) {
                  return `
                  <tr class="hover:bg-gray-50 transition-colors duration-150">
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">${id}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                      <div class="flex items-center">
                        <div class="h-8 w-8 rounded-full bg-gray-200 flex items-center justify-center mr-3">
                          <span class="text-sm font-medium text-gray-600">${id.toString().charAt(0).toUpperCase()}</span>
                        </div>
                        <span class="text-sm font-medium text-gray-900">用户${id}</span>
                      </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600">user${id}@example.com</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                      <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">
                        用户
                      </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                      <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
                        活跃
                      </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                      <button class="text-blue-500 hover:text-blue-700 mr-3 text-sm font-medium">编辑</button>
                      <button class="text-red-500 hover:text-red-700 text-sm font-medium">删除</button>
                    </td>
                  </tr>
                `; 
                }).join('')}
              </tbody>
            </table>
          </div>
        </div>
      `;
      break;
      
    case '/system/config':
      content = `
        <div class="bg-white/90 border border-[rgba(59,130,246,0.4)] rounded-[12px] shadow-[0_4px_12px_rgba(0,0,0,0.02)] p-6">
          <h2 class="text-xl font-bold text-[#334155] mb-6">系统配置</h2>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-[#334155] mb-1">系统名称</label>
                <input type="text" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#3b82f6] focus:border-transparent" value="系统管理平台">
              </div>
              <div>
                <label class="block text-sm font-medium text-[#334155] mb-1">系统版本</label>
                <input type="text" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#3b82f6] focus:border-transparent" value="v1.0.0" readonly>
              </div>
              <div>
                <label class="block text-sm font-medium text-[#334155] mb-1">系统描述</label>
                <textarea class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#3b82f6] focus:border-transparent" rows="3">这是一个功能强大的系统管理平台</textarea>
              </div>
            </div>
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-[#334155] mb-1">主题颜色</label>
                <div class="flex space-x-2">
                  <button class="w-8 h-8 rounded-full bg-blue-500 border-2 border-transparent hover:border-gray-300 transition-all duration-300"></button>
                  <button class="w-8 h-8 rounded-full bg-green-500 border-2 border-transparent hover:border-gray-300 transition-all duration-300"></button>
                  <button class="w-8 h-8 rounded-full bg-purple-500 border-2 border-transparent hover:border-gray-300 transition-all duration-300"></button>
                  <button class="w-8 h-8 rounded-full bg-red-500 border-2 border-transparent hover:border-gray-300 transition-all duration-300"></button>
                </div>
              </div>
              <div>
                <label class="block text-sm font-medium text-[#334155] mb-1">是否开启日志</label>
                <div class="flex items-center space-x-2">
                  <input type="radio" id="log-enabled" name="log" class="w-4 h-4 text-[#3b82f6]" checked>
                  <label for="log-enabled" class="text-sm text-[#334155]">开启</label>
                  <input type="radio" id="log-disabled" name="log" class="w-4 h-4 text-[#3b82f6]">
                  <label for="log-disabled" class="text-sm text-[#334155]">关闭</label>
                </div>
              </div>
            </div>
          </div>
          <div class="flex justify-end space-x-4 mt-6">
            <button class="px-4 py-2 border border-gray-300 text-[#334155] rounded-lg hover:bg-gray-50 transition-colors duration-300">
              取消
            </button>
            <button class="px-4 py-2 bg-[#3b82f6] text-white rounded-lg hover:bg-[#2563eb] transition-colors duration-300">
              保存配置
            </button>
          </div>
        </div>
      `;
      break;
      
    default:
      content = `
        <div class="flex items-center justify-center h-full">
          <div class="text-center">
            <h2 class="text-2xl font-bold text-gray-800 mb-2">404</h2>
            <p class="text-gray-600">页面未找到</p>
          </div>
        </div>
      `;
  }
  
  contentContainer.innerHTML = content;
  contentArea.appendChild(contentContainer);
}



// 切换侧边栏折叠状态
function toggleSidebar() {
  isSidebarCollapsed = !isSidebarCollapsed;
  updateSidebarLayout();
}

// 切换侧边栏显示/隐藏状态
function toggleSidebarVisibility() {
  isSidebarHidden = !isSidebarHidden;
  updateSidebarLayout();
}

// 更新侧边栏布局
function updateSidebarLayout() {
  const sidebar = document.getElementById('sidebar');
  const rightContent = document.getElementById('right-content');
  const collapseBtn = document.getElementById('collapse-btn');
  const title = sidebar?.querySelector('h2');
  const searchContainer = sidebar?.querySelector('.relative')?.parentElement;
  const menuIcons = sidebar?.querySelectorAll('[data-path] span:first-child');
  
  if (sidebar && rightContent && collapseBtn && title) {
    if (isSidebarHidden) {
      // 隐藏侧边栏
      sidebar.style.display = 'none';
      sidebar.style.width = '0';
      rightContent.style.flex = '1';
      rightContent.style.width = '100%';
    } else {
      // 显示侧边栏
      sidebar.style.display = 'flex';
      rightContent.style.flex = '1';
      
      if (isSidebarCollapsed) {
        // 折叠状态
        sidebar.style.width = '64px';
        rightContent.style.width = 'calc(100% - 64px)';
        
        // 折叠状态：图标变蓝
        collapseBtn.classList.add('text-[#3b82f6]', 'bg-[rgba(59,130,246,0.1)]');
        collapseBtn.classList.remove('text-[#64748b]');
        title.style.opacity = '0';
        title.style.width = '0';
        title.style.overflow = 'hidden';
        if (searchContainer) {
          searchContainer.style.display = 'none';
        }
        
        // 调整图标大小
        if (menuIcons) {
          menuIcons.forEach(function(icon: any) {
            icon.style.fontSize = '14px';
            icon.style.marginRight = '0';
          });
        }
        
        // 隐藏菜单文字
        const menuTexts = sidebar.querySelectorAll('[data-path] span:not(:first-child)');
        menuTexts.forEach(function(text: any) {
          text.style.opacity = '0';
          text.style.width = '0';
          text.style.overflow = 'hidden';
          text.style.display = 'none';
        });
      } else {
        // 展开状态
        sidebar.style.width = '256px';
        rightContent.style.width = 'calc(100% - 256px)';
        
        // 展开状态：图标恢复灰色
        collapseBtn.classList.add('text-[#64748b]');
        collapseBtn.classList.remove('text-[#3b82f6]', 'bg-[rgba(59,130,246,0.1)]');
        title.style.opacity = '1';
        title.style.width = 'auto';
        title.style.overflow = 'visible';
        if (searchContainer) {
          searchContainer.style.display = 'block';
        }
        
        // 恢复图标大小
        if (menuIcons) {
          menuIcons.forEach(function(icon: any) {
            icon.style.fontSize = '18px';
            icon.style.marginRight = '12px';
          });
        }
        
        // 显示菜单文字
        const menuTexts = sidebar.querySelectorAll('[data-path] span:not(:first-child)');
        menuTexts.forEach(function(text: any) {
          text.style.opacity = '1';
          text.style.width = 'auto';
          text.style.overflow = 'visible';
          text.style.display = 'inline';
        });
      }
    }
  }
}

// 菜单搜索功能
function filterMenuItems(searchText: string) {
  const menuContainer = document.getElementById('menu-container');
  if (!menuContainer) return;
  
  const menuItems = menuContainer.querySelectorAll('li');
  const searchLower = searchText.toLowerCase().trim();
  
  if (searchLower === '') {
    // 显示所有菜单项
    menuItems.forEach(function(item) {
      item.style.display = 'block';
    });
    return;
  }
  
  menuItems.forEach(function(item) {
    const menuText = item.textContent?.toLowerCase() || '';
    if (menuText.includes(searchLower)) {
      item.style.display = 'block';
      // 确保父级菜单也显示
      let parent = item.parentElement;
      while (parent && parent !== menuContainer) {
        if (parent.tagName === 'LI') {
          parent.style.display = 'block';
        }
        parent = parent.parentElement;
      }
    } else {
      item.style.display = 'none';
    }
  });
}

// 更新左侧菜单选中状态
function updateSidebarActiveState(path: string) {
  const menuLinks = document.querySelectorAll('[data-path]');
  menuLinks.forEach(function(link) {
    const linkPath = link.getAttribute('data-path');
    if (linkPath === path) {
      link.classList.add('bg-[rgba(59,130,246,0.15)]', 'text-[#3b82f6]', 'font-medium', 'border-l-3', 'border-[#3b82f6]');
      link.classList.remove('hover:bg-gray-100', 'text-[#64748b]');
    } else {
      link.classList.remove('bg-[rgba(59,130,246,0.15)]', 'text-[#3b82f6]', 'font-medium', 'border-l-3', 'border-[#3b82f6]');
      link.classList.add('hover:bg-gray-100', 'text-[#64748b]');
    }
  });
}

// 更新面包屑导航
function updateBreadcrumb() {
  const breadcrumb = document.getElementById('breadcrumb');
  if (!breadcrumb) return;
  
  // 清空现有面包屑
  breadcrumb.innerHTML = '';
  
  // 添加首页面包屑
  const homeCrumb = document.createElement('a');
  homeCrumb.href = 'javascript:void(0)';
  homeCrumb.className = 'text-[#64748b] hover:text-[#3b82f6] transition-colors duration-200';
  homeCrumb.textContent = '首页';
  homeCrumb.addEventListener('click', function() {
    openTab('/dashboard', '首页');
  });
  breadcrumb.appendChild(homeCrumb);
  
  // 根据当前路径添加面包屑
  if (currentPath !== '/dashboard') {
    const separator = document.createElement('span');
    separator.className = 'text-[#cbd5e1]';
    separator.textContent = '/';
    breadcrumb.appendChild(separator);
    
    const currentMenu = findMenuItemByPath(currentPath);
    if (currentMenu) {
      const currentCrumb = document.createElement('span');
      currentCrumb.className = 'text-[#334155] font-medium';
      currentCrumb.textContent = currentMenu.name;
      breadcrumb.appendChild(currentCrumb);
    }
  }
}

// 切换主题
function toggleTheme() {
  const themeToggle = document.getElementById('theme-toggle');
  const html = document.documentElement;
  
  if (html.classList.contains('dark')) {
    html.classList.remove('dark');
    themeToggle.innerHTML = '<span class="text-xl">🌙</span>';
    localStorage.setItem('theme', 'light');
  } else {
    html.classList.add('dark');
    themeToggle.innerHTML = '<span class="text-xl">☀️</span>';
    localStorage.setItem('theme', 'dark');
  }
}

// 移动端菜单切换
function toggleMobileMenu() {
  // 在小屏幕设备上使用原来的移动端菜单切换逻辑
  const width = window.innerWidth;
  if (width < 1024) {
    const sidebar = document.getElementById('sidebar');
    const rightContent = document.getElementById('right-content');
    
    if (sidebar && rightContent) {
      if (sidebar.style.display === 'none' || sidebar.style.display === '') {
        // 显示侧边栏
        sidebar.style.display = 'flex';
        sidebar.style.position = 'fixed';
        sidebar.style.zIndex = '1000';
        sidebar.style.left = '0';
        sidebar.style.top = '0';
        sidebar.style.height = '100%';
        sidebar.style.width = '256px';
        sidebar.style.flexDirection = 'column';
        
        // 添加遮罩层
        const overlay = document.createElement('div');
        overlay.id = 'sidebar-overlay';
        overlay.style.position = 'fixed';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.width = '100%';
        overlay.style.height = '100%';
        overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
        overlay.style.zIndex = '999';
        overlay.addEventListener('click', function() {
          toggleMobileMenu();
        });
        document.body.appendChild(overlay);
      } else {
        // 隐藏侧边栏
        sidebar.style.display = 'none';
        
        // 移除遮罩层
        const overlay = document.getElementById('sidebar-overlay');
        if (overlay) {
          overlay.remove();
        }
      }
    }
  } else {
    // 在大屏幕设备上使用新的隐藏/显示功能
    toggleSidebarVisibility();
  }
}

// 绑定用户下拉菜单事件
function bindUserDropdownEvents() {
  const dropdownBtn = document.getElementById('user-dropdown-btn');
  const dropdownMenu = document.getElementById('user-dropdown-menu');
  const dropdownIcon = document.getElementById('user-dropdown-icon');
  
  if (dropdownBtn && dropdownMenu && dropdownIcon) {
    dropdownBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      const isHidden = dropdownMenu.classList.contains('hidden');
      
      if (isHidden) {
        // 显示下拉菜单
        dropdownMenu.classList.remove('hidden');
        dropdownMenu.style.opacity = '1';
        dropdownMenu.style.transform = 'translateY(0)';
        dropdownIcon.style.transform = 'rotate(180deg)';
      } else {
        // 隐藏下拉菜单
        dropdownMenu.classList.add('hidden');
        dropdownMenu.style.opacity = '0';
        dropdownMenu.style.transform = 'translateY(-10px)';
        dropdownIcon.style.transform = 'rotate(0deg)';
      }
    });
    
    // 点击其他地方关闭下拉菜单
    document.addEventListener('click', function() {
      dropdownMenu.classList.add('hidden');
      dropdownMenu.style.opacity = '0';
      dropdownMenu.style.transform = 'translateY(-10px)';
      dropdownIcon.style.transform = 'rotate(0deg)';
    });
    
    // 阻止下拉菜单内部的点击事件冒泡
    dropdownMenu.addEventListener('click', function(e) {
      e.stopPropagation();
    });
  }
}

// 绑定事件
function bindEvents() {
  // 绑定窗口大小变化事件
  window.addEventListener('resize', function() {
    handleResize();
  });
  
  // 绑定用户下拉菜单事件
  bindUserDropdownEvents();
  
  // 初始化主题
  initTheme();
}

// 处理窗口大小变化
function handleResize() {
  const width = window.innerWidth;
  const sidebar = document.getElementById('sidebar');
  const menuToggle = document.getElementById('menu-toggle');
  const rightContent = document.getElementById('right-content');
  
  if (width >= 1024) {
    // 大屏幕：显示侧边栏
    if (sidebar) {
      sidebar.style.display = 'flex';
      sidebar.style.position = 'relative';
      sidebar.style.zIndex = 'auto';
      sidebar.style.left = 'auto';
      sidebar.style.top = 'auto';
      sidebar.style.height = '100%';
      sidebar.style.flexDirection = 'column';
      
      // 移除遮罩层
      const overlay = document.getElementById('sidebar-overlay');
      if (overlay) {
        overlay.remove();
      }
      
      // 根据当前状态更新布局
      updateSidebarLayout();
    }
    if (menuToggle) {
      menuToggle.style.display = 'none';
    }
  } else {
    // 小屏幕：隐藏侧边栏，显示菜单切换按钮
    if (sidebar) {
      sidebar.style.display = 'none';
    }
    if (menuToggle) {
      menuToggle.style.display = 'flex';
    }
    if (rightContent) {
      rightContent.style.width = '100%';
    }
  }
}

// 初始化主题
function initTheme() {
  const savedTheme = localStorage.getItem('theme') || 'light';
  const html = document.documentElement;
  const themeToggle = document.getElementById('theme-toggle');
  
  if (savedTheme === 'dark') {
    html.classList.add('dark');
    if (themeToggle) {
      themeToggle.innerHTML = '<span class="text-xl">☀️</span>';
    }
  } else {
    html.classList.remove('dark');
    if (themeToggle) {
      themeToggle.innerHTML = '<span class="text-xl">🌙</span>';
    }
  }
}

// 初始化折叠按钮状态
function initCollapseButtonState() {
  const collapseBtn = document.getElementById('collapse-btn');
  if (collapseBtn) {
    if (isSidebarCollapsed) {
      collapseBtn.classList.add('text-[#3b82f6]', 'bg-[rgba(59,130,246,0.1)]');
      collapseBtn.classList.remove('text-[#64748b]');
    } else {
      collapseBtn.classList.add('text-[#64748b]');
      collapseBtn.classList.remove('text-[#3b82f6]', 'bg-[rgba(59,130,246,0.1)]');
    }
  }
}

// 更新折叠按钮状态
function updateCollapseButtonState() {
  const collapseBtn = document.getElementById('collapse-btn');
  if (collapseBtn) {
    if (isSidebarCollapsed) {
      collapseBtn.classList.add('text-[#3b82f6]', 'bg-[rgba(59,130,246,0.1)]');
      collapseBtn.classList.remove('text-[#64748b]');
    } else {
      collapseBtn.classList.add('text-[#64748b]');
      collapseBtn.classList.remove('text-[#3b82f6]', 'bg-[rgba(59,130,246,0.1)]');
    }
  }
}

// 初始化应用
function initApp() {
  // 创建页面加载动画
  const loadingScreen = document.createElement('div');
  loadingScreen.className = 'page-loading';
  loadingScreen.innerHTML = `
    <div class="text-center">
      <div class="loading-spinner"></div>
      <div class="loading-text">系统加载中...</div>
    </div>
  `;
  document.body.appendChild(loadingScreen);

  // 加载菜单数据
  loadMenuData().then(function() {
    // 创建完整的后台管理系统布局
    createAdminLayout();
    // 绑定事件
    bindEvents();
    
    // 初始化折叠按钮状态
    initCollapseButtonState();
    
    // 初始化侧边栏布局
    updateSidebarLayout();
    
    // 添加页面过渡动画
    const contentArea = document.getElementById('content-area');
    if (contentArea) {
      contentArea.classList.add('page-transition');
    }
    
    // 隐藏加载动画
    setTimeout(function() {
      loadingScreen.classList.add('hidden');
      setTimeout(function() {
        loadingScreen.remove();
      }, 500);
    }, 1000);
  });
}

// 启动应用
initApp();
